﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace ResourceTypeConfigurationApp
{
    public partial class fmNewResourceObject : Form
    {
        public fmNewResourceObject()
        {
            InitializeComponent();
        }

        private void fmNewResourceObject_Load(object sender, EventArgs e)
        {
            DataTable dtPushType = new DataTable();
            dtPushType.Columns.Add("VALUE", typeof(string));
            dtPushType.Columns.Add("TEXT", typeof(string));
            dtPushType.Rows.Add(new object[] { "0", "不向资源表推送" });
            dtPushType.Rows.Add(new object[] { "1", "华云" });
            dtPushType.Rows.Add(new object[] { "2", "总平台" });
            dtPushType.Rows.Add(new object[] { "3", "都需要" });

            this.cbxPushType.ValueMember = "VALUE";
            this.cbxPushType.DisplayMember = "TEXT";
            this.cbxPushType.DataSource = dtPushType;
            this.cbxPushType.SelectedIndex = 0;

            DataTable dtResourceType = new DataTable();
            dtResourceType.Columns.Add("VALUE", typeof(string));
            dtResourceType.Columns.Add("TEXT", typeof(string));
            dtResourceType.Rows.Add(new object[] { "", "" });


            this.cbxResourceType.ValueMember = "VALUE";
            this.cbxResourceType.DisplayMember = "TEXT";
            this.cbxResourceType.DataSource = dtResourceType;
        }

        private async void btnNew_Click(object sender, EventArgs e)
        {

            DataTable dtSite = SiteBindingSource.DataSource as DataTable;


            if (dtSite == null || !dtSite.AsEnumerable().Any(x => x["IsSelected"].ToString() == "True"))
            {
                MessageBox.Show("请先勾选数据");
                return;
            }

            var drSite = dtSite.AsEnumerable().FirstOrDefault(x => x["IsSelected"].ToString() == "True");

            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA == null || !dtA.AsEnumerable().Any(x => x["IsSelected"].ToString() == "True"))
            {
                MessageBox.Show("请先勾选数据");
                return;
            }

            if (cbxResourceType.Text == "")
            {
                MessageBox.Show("请选择自定义资源类型");
                return;
            }


            if (string.IsNullOrWhiteSpace(txtPtDate.Text) || string.IsNullOrWhiteSpace(txtWhDate.Text))
            {
                MessageBox.Show("更新时间不可为空！");
                return;
            }
            string format = "yyyyMMdd";
            if (!DateTime.TryParseExact(txtPtDate.Text, format, null, System.Globalization.DateTimeStyles.None, out DateTime PtDate))
            {
                MessageBox.Show("功率更新时间的时间格式错误！");
                return;
            }
            if (!DateTime.TryParseExact(txtWhDate.Text, format, null, System.Globalization.DateTimeStyles.None, out DateTime WhDate))
            {
                MessageBox.Show("电量更新时间的时间格式错误！");
                return;
            }
            int isDel = 1;
            if (cbOn.Checked)
            {
                isDel = 0;
            }

            var drs = dtA.AsEnumerable().Where(x => x["IsSelected"].ToString() == "True");
            var ids = drs.Select(x => x["ID"].ToString()).ToList();

            var dtResourceObject = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id,factory_station_id,custom_resource_type_id FROM custom_resource_object WHERE custom_resource_type_id={MySQLHelper.ConvertGuidToSql(cbxResourceType.SelectedValue.ToString())} and factory_station_id IN ({MySQLHelper.ConvertListToStr(ids)})");
            if (dtResourceObject != null && dtResourceObject.Rows.Count > 0)
            {
                MessageBox.Show($@"已存在资源对象{string.Join(",", dtResourceObject.AsEnumerable().Select(x => x["factory_station_id"].ToString()))}！");
                return;
            }


            List<string> sqlList = new List<string>();
            //插入数据
            foreach (var item in dtA.AsEnumerable().Where(x => x["IsSelected"].ToString() == "True"))
            {
                int range_type = 1;
                if (item["CLASSNAME"].ToString() == "Filiale")
                {
                    range_type = 0;
                }
                sqlList.Add($@"insert into custom_resource_object(range_type,factory_station_id,fname,custom_no,custom_resource_type_id,parent_factory_station_id,create_time,update_time,deleted,push_type)VALUES ({range_type},{MySQLHelper.ConvertGuidToSql(item["ID"].ToString())},{MySQLHelper.ConvertGuidToSql(item["NAME"].ToString())},{MySQLHelper.ConvertGuidToSql(txtCustomNo.Text)},{MySQLHelper.ConvertGuidToSql(cbxResourceType.SelectedValue.ToString())},{MySQLHelper.ConvertGuidToSql(txtParentID.Text)},NOW(),NOW(),{isDel},{MySQLHelper.ConvertGuidToSql(cbxPushType.SelectedValue.ToString())})");
            }
            sqlList.Add($@"INSERT into custom_object_value_type_time(custom_resource_object_id,data_value_type,update_day)SELECT id,0,'{PtDate}' from custom_resource_object where factory_station_id IN({MySQLHelper.ConvertListToStr(ids)}) AND custom_resource_type_id={MySQLHelper.ConvertGuidToSql(cbxResourceType.SelectedValue.ToString())} ");
            sqlList.Add($@"INSERT into custom_object_value_type_time(custom_resource_object_id,data_value_type,update_day)SELECT id,1,'{WhDate}' from custom_resource_object where factory_station_id IN({MySQLHelper.ConvertListToStr(ids)}) AND custom_resource_type_id={MySQLHelper.ConvertGuidToSql(cbxResourceType.SelectedValue.ToString())} ");
            if (await MySQLHelper.ExecuteSqlAsync(MySQLHelper.targetConnectionString, sqlList))
            {
                MessageBox.Show("新建资源对象成功");
            }
            else
            {
                MessageBox.Show("新建资源对象失败");
            }
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            var dtA = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id,`site_name`,pkey,parent_pkey FROM site_15min WHERE `site_name` LIKE '%{txtSiteName.Text}%'");
            if (dtA == null || dtA.Rows.Count == 0)
            {
                MessageBox.Show("没有查询到相关数据");
                return;
            }
            if (!dgSite.Columns.Contains("IsSelected"))
            {
                // 创建一个DataGridViewCheckBoxColumn
                DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
                checkBoxColumn.HeaderText = "选中";
                checkBoxColumn.Name = "IsSelected";
                checkBoxColumn.DataPropertyName = "IsSelected";
                // 将勾选列添加到DataGridView
                dgSite.Columns.Add(checkBoxColumn);
            }

            // 为DataTable添加对应的列
            dtA.Columns.Add("IsSelected", typeof(bool));
            dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

            // 设置不允许新增行
            dgSite.AllowUserToAddRows = false;

            dgSite.AllowUserToDeleteRows = false; // 禁止删除行

            SiteBindingSource.DataSource = dtA;
            dgSite.DataSource = SiteBindingSource;

            dgSite.Columns["id"].HeaderText = "ID";
            dgSite.Columns["site_name"].HeaderText = "名称";
            dgSite.Columns["pkey"].HeaderText = "数元平台站点ID";
            dgSite.Columns["parent_pkey"].HeaderText = "数元上级节点ID";
            dgSite.AutoResizeColumns();

            dgSite.CellContentClick += dgSite_CellContentClick;


            
            if (!dgDevice.Columns.Contains("IsSelected"))
            {
                // 创建一个DataGridViewCheckBoxColumn
                DataGridViewCheckBoxColumn checkBoxColumn2 = new DataGridViewCheckBoxColumn();
                checkBoxColumn2.HeaderText = "选中";
                checkBoxColumn2.Name = "IsSelected";
                checkBoxColumn2.DataPropertyName = "IsSelected";
                // 将勾选列添加到DataGridView
                dgDevice.Columns.Add(checkBoxColumn2);
            }
            

            // 设置不允许新增行
            dgDevice.AllowUserToAddRows = false;

            dgDevice.AllowUserToDeleteRows = false; // 禁止删除行

            dgDevice.ContextMenuStrip = contextMenuStrip1;
        }

        private async void dgSite_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查点击的是否是IsSelected列
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == dgSite.Columns["IsSelected"].Index)
                {
                    for (int i = 0; i < dgSite.Rows.Count; i++)
                    {
                        if (i != e.RowIndex)
                        {
                            // 取消其他行IsSelected列的勾选
                            dgSite.Rows[i].Cells["IsSelected"].Value = false;
                        }
                    }
                    //var dr = SiteBindingSource.Current as DataRowView;
                    DataRowView drv = SiteBindingSource[e.RowIndex] as DataRowView;
                    if (drv == null)
                    {
                        return;
                    }
                    DataTable dtResourceType = new DataTable();
                    dtResourceType.Columns.Add("VALUE", typeof(string));
                    dtResourceType.Columns.Add("TEXT", typeof(string));
                    dtResourceType.Rows.Add(new object[] { "", "" });
                    //查询分类
                    var dtResourceTypeData = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id,type_name FROM custom_resource_type WHERE factory_station_id is null or factory_station_id={MySQLHelper.ConvertDecimalToSql(drv["pkey"].ToString())} order by range_type,id");
                    foreach (DataRow drType in dtResourceTypeData.Rows)
                    {
                        dtResourceType.Rows.Add(new object[] { drType["id"].ToString(), drType["type_name"].ToString() });
                    }
                    this.cbxResourceType.ValueMember = "VALUE";
                    this.cbxResourceType.DisplayMember = "TEXT";
                    this.cbxResourceType.DataSource = dtResourceType;


                    var dtA = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.soureConnectionString, $@"SELECT ID,CLASSNAME,`NAME`,PATHID FROM  dev_powersystemresource where (PATHID like '\\\\{drv["pkey"]}%' OR ID={drv["pkey"]}) AND CLASSNAME IN( 'FactoryStation','Filiale' ) order by PATHID");
                    if (dtA.Rows.Count == 0)
                    {
                        MessageBox.Show("没有查询到相关数据");
                        return;
                    }
                    // 为DataTable添加对应的列
                    dtA.Columns.Add("IsSelected", typeof(bool));
                    dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

                    DeviceBindingSource.DataSource = dtA;
                    dgDevice.DataSource = DeviceBindingSource;

                    dgDevice.Columns["ID"].HeaderText = "ID";
                    dgDevice.Columns["CLASSNAME"].HeaderText = "类型";
                    dgDevice.Columns["NAME"].HeaderText = "名称";
                    dgDevice.Columns["PATHID"].HeaderText = "路径";
                    dgDevice.AutoResizeColumns();
                    lbCount.Text = dtA.Rows.Count.ToString();
                }
            }

        }


        private void txtEndDate_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void tsmAllSelect_Click(object sender, EventArgs e)
        {
            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA != null && dtA.Rows.Count > 0)
            {
                //for (int i = 0; i < dgDevice.Rows.Count; i++)
                //{
                //    // 取消其他行IsSelected列的勾选
                //    dgDevice.Rows[i].Cells["IsSelected"].Value = true;
                //}

                foreach (var dr in dtA.AsEnumerable())
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    dr["IsSelected"] = true;
                    dr.EndEdit();
                }
                dgDevice.EndEdit();

            }
        }

        private void tsmAllCancel_Click(object sender, EventArgs e)
        {
            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA != null && dtA.Rows.Count > 0)
            {
                //for (int i = 0; i < dgDevice.Rows.Count; i++)
                //{
                //    // 取消其他行IsSelected列的勾选
                //    dgDevice.Rows[i].Cells["IsSelected"].Value = true;
                //}

                foreach (var dr in dtA.AsEnumerable())
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    dr["IsSelected"] = false;
                    dr.EndEdit();
                }
                dgDevice.EndEdit();

            }
        }



        private void txtParentID_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 允许输入数字、退格键
            if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
            {
                e.Handled = true;
            }
        }
    }
}
